/*
 * @Author: wangdazhuang
 * @Date: 2024-08-29 19:31:14
 * @LastEditTime: 2025-01-27 11:39:42
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/views/player/controllers/common_video_play_controller.dart
 */

import 'dart:async';
import 'package:get/get.dart';
import 'package:media_kit/media_kit.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:pornhub_app/utils/logger.dart';

class CommonVideoPlayerController extends GetxController {
  bool playerInitialized = false;
  VideoController? playerVC;
  Player? player;

  ///播放结束
  StreamSubscription<bool>? _endSubs;
  double asp = 16.0 / 9.0;

  //初始化播放器
  void _initAction() {
    String playPath = Get.arguments;
    final param = Get.parameters["asp"];
    asp = double.tryParse(param ?? '') ?? asp;
    assert(playPath.isNotEmpty, 'init player failed,play URL empty!');
    logger.d('播放地址>>>>:$playPath');
    final config = PlayerConfiguration(
      muted: false,
      title: '',
      osc: true,
      ready: () {
        playerInitialized = true;
        update();
      },
    );
    player = Player(configuration: config);
    playerVC = VideoController(player!);

    ///播放结束监听
    _endSubs = player!.stream.completed.listen((e) {
      if (e) {
        player!.seek(const Duration(seconds: 0)).then((_) {
          player!.play();
        });
      }
    });

    player?.open(Media(playPath));
  }

  @override
  void onClose() {
    _endSubs?.cancel();
    player?.dispose();
    super.onClose();
  }

  @override
  void onInit() {
    super.onInit();
    _initAction();
  }
}
